﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlCommandHelper
{
    internal class StoredValueInvoker
    {
        Dictionary<Type, Func<string, object>> TypeList = new Dictionary<Type, Func<string, object>>();

        /// <summary>
        /// Invoke the correct method to get the typed value
        /// </summary>
        /// <param name="type">type</param>
        /// <param name="parameterName">parameter name</param>
        /// <returns>object</returns>
        public object Invoke(Type type, string parameterName)
        {
            try
            {
                if (string.IsNullOrEmpty(parameterName))
                    throw new ArgumentNullException("parameterName", "cannot be null or empty");

                return TypeList[type].Invoke(parameterName);
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// Create new instance of <see cref="StoredValueInvoker"/> class.
        /// </summary>
        /// <param name="reader">the Datareader</param>
        public StoredValueInvoker(IDataReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            //initializes the list of types and methods to be Invoked 
            TypeList.Add(typeof(string), (x) => { return reader.TryGetString(x); });
            TypeList.Add(typeof(int), (x) => { return reader.TryGetInt32(x); });
            TypeList.Add(typeof(Int64), (x) => { return reader.TryGetInt64(x); });
            TypeList.Add(typeof(Guid), (x) => { return reader.TryGetGuid(x); });
            TypeList.Add(typeof(DateTime), (x) => { return reader.TryGetDateTime(x); });
            TypeList.Add(typeof(bool), (x) => { return reader.TryGetBoolean(x); });
            TypeList.Add(typeof(double), (x) => { return reader.TryGetDouble(x); });
        }
    }
}
